package com.humanminoritygame.web;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.humanminoritygame.model.Category;
import com.humanminoritygame.model.CategoryRepo;
import com.humanminoritygame.model.Question;
import com.humanminoritygame.model.QuestionRepo;
import com.humanminoritygame.model.Room;
import com.humanminoritygame.model.RoomRepo;
import com.humanminoritygame.model.Subscription;
import com.humanminoritygame.model.SubscriptionRepo;
import com.humanminoritygame.model.User;
import com.humanminoritygame.model.UserRepo;
import com.humanminoritygame.model.UserRoundResultRepo;

@Controller
public class SubscriptionController {
  SubscriptionRepo subsciptions;
  QuestionRepo questions;
  CategoryRepo categories;
  UserRepo users;
  RoomRepo rooms;
  UserRoundResultRepo userRoundResults;
  SessionFactory sessionFactory;

  @Autowired
  public SubscriptionController(SubscriptionRepo subscriptions, QuestionRepo questions, CategoryRepo categories, UserRepo users, RoomRepo rooms, UserRoundResultRepo userRoundResults, SessionFactory sessionFactory){
    this.users = users;
    this.subsciptions = subscriptions;
    this.questions = questions;
    this.categories = categories;
    this.rooms = rooms;
    this.userRoundResults = userRoundResults;
    this.sessionFactory = sessionFactory;
  }

  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView list(HttpSession session){
    ModelAndView mav = new ModelAndView();
    mav.setViewName("subscriptionList");
    User user = (User)session.getAttribute("user");
    Set <Subscription> subs = this.subsciptions.getOpenSubscriptions(user); 
    mav.addObject("subscriptions", subs);
    
    mav.addObject("questions", questions.getAllQuestions());
    mav.addObject("categories", categories.getAllCategories());
    
    return mav;
  }
  
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView list2(HttpSession session){
    ModelAndView mav = new ModelAndView();
    mav.setViewName("subscriptionList");
    User user = (User)session.getAttribute("user");
    Set <Subscription> subs = this.subsciptions.getOpenSubscriptions(user); 
    mav.addObject("subscriptions", subs);
    
    mav.addObject("questions", questions.getAllQuestions());
    mav.addObject("categories", categories.getAllCategories());

    return mav;
  }
  
  @RequestMapping(method = RequestMethod.POST)
  public String add(HttpServletRequest request, HttpSession session, @RequestParam("question") Long questionId, @RequestParam("category") Long categoryId  ){
    User user = (User)session.getAttribute("user");
    Category category = categories.getCategoryById(categoryId);
    if(subsciptions.getSubscription(user, category)!= null){
      request.setAttribute("subscriptionerror", "You are already subscribed to that category<br/>");
      return "forward:list2";
    }

    Room room = category.getAvailableRoom();
    Question question = questions.getQuestionById(questionId);
    if(room.isEmpty()){
      rooms.addRoom(room);
      subscribeTheRobots(room);
      room.addRound();
    }
    subsciptions.addSubscription(new Subscription(room, user, question));
    return "redirect:../room/history?id=" + room.getId() + "&error=0";
  }

  private void subscribeTheRobots(Room room){
    Question question = questions.getAllQuestions().iterator().next();
    Set<User> robots = users.getRobots();
    for(User r : robots){
      subscribeRobot(r, room, question);
    }
  }

  private void subscribeRobot(User user, Room room, Question question){
    if(!room.isSubscribed(user)){
      Subscription subscription = new Subscription(room, user, question);
      subsciptions.addSubscription(subscription);
    }
  }
  
  
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView listOld(HttpSession session){
    ModelAndView mav = new ModelAndView();
    mav.setViewName("subscriptionListOld");
    User user = (User)session.getAttribute("user");
    Set <Subscription> subs = this.subsciptions.getClosedSubscriptions(user); 
    mav.addObject("subscriptions", subs);
    return mav;
  }
  
  
  @RequestMapping(method = RequestMethod.GET)
  public void getTime(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") Long categoryId, @RequestParam("image") Double number){
    String xml = new String("<?xml version='1.0' encoding='ISO-8859-1'?>");
    response.setContentType("text/xml");
    Category category = categories.getCategoryById(categoryId);
    Room room = category.getAvailableExistingRoom();
    xml= xml + "<time>";
    if(category == null || room == null){
      xml = xml + "0";
    } else{
      xml = xml + room.getRemainingTimeForSubscription();
    }
    xml = xml + "</time>";

    try {
      ServletOutputStream out = response.getOutputStream();
      out.write(xml.getBytes());
      out.flush();
      out.close();
    } catch (IOException e) {
      throw new RuntimeException();
    }
  }
  
  
}
